package com.ithuangyl.common.web.base;

import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;

import androidx.core.content.FileProvider;

import com.ithuangyl.common.web.callback.IFileChooserInterface;
import com.ithuangyl.common.web.callback.IWebViewInitializer;
import com.ithuangyl.common.web.chromeclient.PhotoUtils;
import com.ithuangyl.common.web.chromeclient.WebChromeClientImpl;
import com.ithuangyl.common.web.client.WebViewClientImpl;
import com.ithuangyl.common.web.event.EventManager;
import com.ithuangyl.common.web.event.ShareEvent;

import java.io.File;

/**
 * author : itHuang
 * e-mail : ithuangyl@163.com
 * date   : 2020/6/22 11:59
 */
public class WebViewActivityImpl extends BaseWebViewActivity implements IWebViewInitializer, IFileChooserInterface {


    private Uri imageUri = null;

    @Override
    protected void initWebEvent() {
        EventManager.getInstance().addEvent("share", new ShareEvent());
    }

    @Override
    public IWebViewInitializer setInitializer() {
        return this;
    }

    @Override
    public void onBindView(Bundle savedInstanceState) {
        getWebView().loadUrl(getUrl());
    }

    @Override
    public BaseWebView initWebView(BaseWebView webView) {
        return new WebViewInitializer().createWebView(webView);
    }

    @Override
    public WebViewClient initWebViewClient() {
        final WebViewClientImpl client = new WebViewClientImpl(this);
//        client.setPageLoadListener(mIPageLoadListener);
        return client;
    }

    @Override
    public WebChromeClient initWebChromeClient() {
        return new WebChromeClientImpl(getWebView(), this);
    }

    @Override
    public void onShowFileChooser(ValueCallback uploadMsg, String acceptType, String capture, BaseWebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        takePhoto();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
        imageUri = Uri.fromFile(fileUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileProvider", fileUri);//通过FileProvider创建一个content类型的Uri
        }
        PhotoUtils.takePicture(this, imageUri, Constant.PHOTO_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ValueCallback<Uri> uploadMessage = getWebView().mUploadMessage;
        ValueCallback<Uri[]> uploadCallbackAboveL = getWebView().mUploadCallbackAboveL;
        if (requestCode == Constant.PHOTO_REQUEST) {
            if (null == uploadMessage && null == getWebView().mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data, uploadCallbackAboveL);
                getWebView().mUploadCallbackAboveL = null;
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                getWebView().mUploadMessage = null;
            }
        }
    }

    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data, ValueCallback<Uri[]> uploadCallbackAboveL) {
        if (requestCode != Constant.PHOTO_REQUEST || uploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                    clipData = data.getClipData();
                }
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        uploadCallbackAboveL.onReceiveValue(results);
    }
}
